package cn.tjnext.apply.utils;

import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptHelper {

    public static String encodeMD5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if (StringUtils.isEmpty(str)) {
            return "";
        }

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(str.getBytes(Charset.forName("UTF-8")));
        byte[] hash = md5.digest();
        StringBuilder sb = new StringBuilder();
        for (byte aHash : hash) {
            if ((0xff & aHash) < 0x10) {
                sb.append("0").append(Integer.toHexString((0xFF & aHash)));
            } else {
                sb.append(Integer.toHexString(0xFF & aHash));
            }
        }

        return sb.toString();
    }
}
